package com.zhq.utils;

import android.os.Environment;
import android.webkit.WebResourceResponse;

import com.zhq.apputil.utils.LogUtil;
import com.zhq.apputil.utils.StringUtil;
import com.zhq.okhttp.ApiServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * @author ZHQ
 * @create 2019/7/3
 * @Describe
 */
public class FileCacheUtils {
    public static final String WEB_VIEW_CACHE = Environment.getExternalStorageDirectory() + File.separator
            + "com.cndz" + File.separator + "webViewCache";

    public static final String TARGET = WEB_VIEW_CACHE + File.separator;

    public static WebResourceResponse getResource(String fileName) {
        String mMimeType = "";
        if (fileName.contains(".js")) {
            mMimeType = "application/x-javascript";
        } else if (fileName.contains(".css")) {
            mMimeType = "text/css";
        }
        if (!StringUtil.isEmpty(mMimeType)) {
            try {
                FileInputStream fileInputStream = FileCacheUtils.getStream(fileName);
                return new WebResourceResponse(mMimeType, "UTF-8", fileInputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /****
     * 下载文件
     * @param url
     * @param name
     */
    public static void downFile(String url, String name, CompositeDisposable disposables) {
        File jsDir = new File(WEB_VIEW_CACHE);
        if (!jsDir.exists()) {
            jsDir.mkdirs();
        }
        disposables.add(ApiServer.getNetService().downloadFile(url).map(new Function<ResponseBody, String>() {
            @Override
            public String apply(ResponseBody responseBody) throws Exception {
                String filePath = new StringBuilder(TARGET).append(name).toString();
                File file = saveFile(filePath, responseBody);
                return file.getPath();
            }
        }).subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())//子线程访问网络
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        LogUtil.e("down success:" + s);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtil.e("down failure:" + throwable.getLocalizedMessage());
                    }
                }));

    }


    /***
     * 文件是否存在
     * @param fileName
     * @return
     */
    public static boolean isFileExist(String fileName) {
        String filePath = new StringBuilder(TARGET).append(fileName).toString();
        File file = new File(filePath);
        return file.exists();
    }

    public static FileInputStream getStream(String fileName) throws IOException {
        String filePath = new StringBuilder(TARGET).append(fileName).toString();
        return new FileInputStream(new File(filePath));
    }


    public static File saveFile(String filePath, ResponseBody body) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File file = null;
        try {
            if (filePath == null) {
                return null;
            }
            file = new File(filePath);
            if ( !file.exists()) {
                file.createNewFile();
            }
            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;
            byte[] fileReader = new byte[4096];
            inputStream = body.byteStream();
            outputStream = new FileOutputStream(file);
            while (true) {
                int read = inputStream.read(fileReader);
                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);
                fileSizeDownloaded += read;
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 递归删除文件和文件夹
     *
     * @param file 要删除的根目录
     */
    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
                return;
            }
            if (file.isDirectory()) {
                File[] childFile = file.listFiles();
                if (childFile == null || childFile.length == 0) {
                    file.delete();
                    return;
                }
                for (File f : childFile) {
                    deleteFile(f);
                }
                file.delete();
            }
        }
    }
}
